import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  ConversationRecordListCommand,
  getConversationRecordListApi,
  exportConversationRecordExcelApi,
  deleteConversationRecordApi
} from "@/api/bot/conversation-record";

export function useConversationRecordHook() {
  const defaultSort: Sort = {
    prop: "createTime",
    order: "descending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.beginTime && searchFormParams.endTime) {
        return [searchFormParams.beginTime, searchFormParams.endTime];
      }
      return null;
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.beginTime = v[0];
        searchFormParams.endTime = v[1];
      } else {
        searchFormParams.beginTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });

  const searchFormParams = reactive<ConversationRecordListCommand>({
    spoken: "",
    receivedName: "",
    groupName: "",
    roomType: "",
    answer: ""
  });

  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);
  const sortState = ref<Sort>(defaultSort);

  // 在hook.tsx中找到columns定义处修改
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "ID",
      prop: "id",
      minWidth: 80
    },
    {
      label: "发言内容",
      prop: "spoken",
      minWidth: 200
    },
    {
      label: "接收者",
      prop: "receivedName",
      minWidth: 120
    },
    {
      label: "群组名称",
      prop: "groupName",
      minWidth: 120
    },
    {
      label: "房间类型",
      prop: "roomType",
      minWidth: 120,
      formatter: row => {
        const roomTypeMap = {
          "1": "外部群",
          "2": "外部联系人",
          "3": "内部群",
          "4": "内部联系人"
        };
        return roomTypeMap[row.roomType] || row.roomType;
      }
    },
    {
      label: "回答内容",
      prop: "answer",
      minWidth: 200
    },
    {
      label: "token消耗",
      prop: "tokenUse",
      minWidth: 100
    },
    {
      label: "创建时间",
      minWidth: 160,
      prop: "createTime",
      sortable: "custom",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  async function getConversationRecordList() {
    pageLoading.value = true;
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);

    const { data } = await getConversationRecordListApi(
      toRaw(searchFormParams)
    ).finally(() => {
      pageLoading.value = false;
    });

    dataList.value = data.rows;
    pagination.total = data.total;
  }

  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    pagination.currentPage = 1;
    getConversationRecordList();
  }

  async function onSearch(tableRef) {
    tableRef.getTableRef().sort("createTime", "descending");
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    formEl.resetFields();
    searchFormParams.beginTime = undefined;
    searchFormParams.endTime = undefined;
    onSearch(tableRef);
  }

  async function exportAllExcel() {
    await exportConversationRecordExcelApi(
      toRaw(searchFormParams),
      `会话记录_${new Date().getTime()}.xlsx`
    );
  }

  async function handleDelete(row) {
    await deleteConversationRecordApi([row.id]);
    message("删除成功", { type: "success" });
    getConversationRecordList();
  }

  async function handleBulkDelete(tableRef) {
    const ids = tableRef
      .getTableRef()
      .getSelectionRows()
      .map(item => item.id);
    if (ids.length === 0) {
      message("请选择要删除的记录", { type: "warning" });
      return;
    }
    await deleteConversationRecordApi(ids);
    message("删除成功", { type: "success" });
    getConversationRecordList();
  }

  onMounted(() => {
    getConversationRecordList();
  });

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    timeRange,
    defaultSort,
    multipleSelection,
    onSearch,
    resetForm,
    onSortChanged,
    exportAllExcel,
    getConversationRecordList,
    handleDelete,
    handleBulkDelete
  };
}
